package com.xenstra.bhavcopydownloader;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class Utils {

	public static String getDoubleDigitString(int value) {
		return (value > 9 ? String.valueOf(value) : "0" + value);
	}

	public static Calendar convertToCalendar(String dateString) {
		try {
			SimpleDateFormat df = new SimpleDateFormat("dd/MMM/yyyy");
			Calendar startDate;
			startDate = new GregorianCalendar();
			startDate.setTime(df.parse(dateString));
			return startDate;
		} catch (ParseException pe) {
			throw new RuntimeException(pe);
		}
	}

	public static File unzipFileInTempFolder(String zipFileName) throws Exception{

		String outputFolder = System.getProperty("java.io.tmpdir");
		File unzippedFile = null;
		// get the zip file content
		ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFileName));
		// get the zipped file list entry
		ZipEntry ze = zis.getNextEntry();
		while (ze != null) {

			String fileName = ze.getName();
			File newFile = new File(outputFolder + File.separator + fileName);

			unzippedFile = newFile;

			// create all non exists folders
			// else you will hit FileNotFoundException for compressed folder
			new File(newFile.getParent()).mkdirs();

			FileOutputStream fos = new FileOutputStream(newFile);

			int len;
			byte[] buffer = new byte[1024];
			while ((len = zis.read(buffer)) > 0) {
				fos.write(buffer, 0, len);
			}

			fos.close();
			ze = zis.getNextEntry();
		}

		zis.closeEntry();
		zis.close();


		return unzippedFile;
	}

	public static List<File> getAllFilesInFolder(String rootFolder, String fileExtension){

		List<File> files = new LinkedList<File>();

		File[] faFiles = new File(rootFolder).listFiles();
		if(faFiles != null && faFiles.length > 0){
			for(File file: faFiles){
				if(file.isFile() && file.getName().matches(fileExtension)){
					files.add(file);
				}
				if(file.isDirectory()){
					files.addAll(getAllFilesInFolder(file.getAbsolutePath(), fileExtension));
				}
			}
		}
		return files;
	}
	
	/**
	 * Returns a list of files whose names have dates that lie between the start date and end date.
	 * 
	 * @param rootFolder
	 * @param startDate
	 * @param endDate
	 * @return
	 */
	public static List<File> getAllFilesInFolder(String rootFolder, Date startDate, Date endDate){

		long startTime = startDate.getTime();
		long endTime = endDate.getTime();
		List<File> files = new LinkedList<File>();

		File[] faFiles = new File(rootFolder).listFiles();
		if(faFiles != null && faFiles.length > 0){
			for(File file: faFiles){
				if(file.isFile()){
					try {
						long fileTime = extractDate(new StringBuilder(file.getName())).getTime();
						if(startTime <= fileTime && fileTime <= endTime){
							files.add(file);
						}
					} catch (ParseException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
				if(file.isDirectory()){
					files.addAll(getAllFilesInFolder(file.getAbsolutePath(), startDate, endDate));
				}
			}
		}
		return files;
	}
	
	public static Date extractDate(StringBuilder source) throws ParseException{
		// the input string format is xxDDMMMYYYYbhav.csv.zip
		
		source.delete(0, 2).delete(source.length() - 12, source.length());
		
		//System.out.println(source);
		SimpleDateFormat sdf = new SimpleDateFormat("ddMMMyyyy");
		
		return sdf.parse(source.toString());
		
	}
	
	public static void main(String[] ar) throws ParseException{
		System.out.println(extractDate(new StringBuilder("cm03MAR2014bhav.csv.zip")));
		@SuppressWarnings("deprecation")
		List<File> files = getAllFilesInFolder("E:\\bhavcopies\\2014",
				new Date(114,0,30), new Date(114,1,20));
		for(File file : files){
			System.out.println(file.getName());
		}
	}
}
